package com.epro.dx.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.fragment.ShoppingCartFragment;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.ImageLoaderUtils;
import com.epro.dx.widget.AddSubtracterView;
import com.epro.dx.widget.AddSubtracterView.OnNumChangeListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.facade.model.OrderProductModel.SalesLimit;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

/**
 * 购物车商品列表适配器
 *
 * @author hjd008
 * @version [版本号, 2015-1-9]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ShoppingCartAdapter extends BaseAdapter implements OnNumChangeListener {

    private Context mContext;

    private List<OrderProductModel> productModels;

//    Map<Integer, SalesLimitModel> limitMap;

    FavoriteBtnListenner btnListenner;

    private OnProductChangeListenner changeListenner;

    private boolean isShoppingCart;

    private int densityDpi;

    private boolean isWifi;

    private DisplayImageOptions options;

    private String currencyCode;

    private String currencyCodeStr;

    private Map<Integer, Boolean> cbSelectes = new HashMap<Integer, Boolean>();

    //    public ShoppingCartAdapter(Context context,OnProductChangeListenner changeListenner, List<OrderProductModel> productModels,
//        Map<Integer, SalesLimitModel> limitMap,boolean isShoppingCart,int densityDpi,boolean isWifi)
    public ShoppingCartAdapter(Context context, OnProductChangeListenner changeListenner, List<OrderProductModel> productModels,
                               boolean isShoppingCart, int densityDpi, boolean isWifi) {
        this.mContext = context;
        //this.fragment = fragment;
        this.changeListenner = changeListenner;
        this.productModels = productModels;
//        this.limitMap = limitMap;
        this.isShoppingCart = isShoppingCart;
        this.densityDpi = densityDpi;
        this.isWifi = isWifi;
        options = ImageLoaderUtils.getImageLoaderOptions(R.drawable.item_default, R.drawable.item_default);

    }

    /**
     * 根据网络连接状态及屏幕像素密度获取图片URL地址
     *
     * @param densityDpi
     * @param product
     * @param defaultDpi1
     * @param defaultDpi2
     * @return
     */
    protected String getImageUrl(int densityDpi, OrderProductModel product, int defaultDpi1, int defaultDpi2) {
        String productIconUrl = null;
        if (densityDpi >= defaultDpi1) {
            if (isWifi) {
                productIconUrl = product.getMediumPictureURL();
            } else {
                if (densityDpi >= defaultDpi2) {
                    productIconUrl = product.getMediumPictureURL();
                } else {
                    productIconUrl = product.getSmallPictureURL();
                }
            }

        } else {
            productIconUrl = product.getSmallPictureURL();
        }
        if (null == productIconUrl || "".equals(productIconUrl)) {
            productIconUrl = product.getSmallPictureURL();
        }
        if (null == productIconUrl || "".equals(productIconUrl)) {
            productIconUrl = product.getMediumPictureURL();
        }
        return productIconUrl;
    }

    @Override
    public int getCount() {
        return null == productModels ? 0 : productModels.size();
    }

    @Override
    public OrderProductModel getItem(int position) {
        //return null == productModels ? null : productModels.get(position);
        if (null != productModels && productModels.size() != 0) {
            return productModels.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (null == productModels || position >= productModels.size()) {
            return null;
        }
        final OrderProductModel productModel = productModels.get(position);
        final ViewHolder viewHolder;
        if (null == convertView) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_shoppingcart, null);
            viewHolder.productThmb = (ImageView) convertView.findViewById(R.id.shoppingcart_item_product_thumb);
            viewHolder.productName = (TextView) convertView.findViewById(R.id.shoppingcart_item_product_name);
            viewHolder.productPrice = (TextView) convertView.findViewById(R.id.shoppingcart_item_product_price);
            viewHolder.productFree = (TextView) convertView.findViewById(R.id.shoppingcart_item_product_free);
            viewHolder.addSubtracterView =
                    (AddSubtracterView) convertView.findViewById(R.id.shoppingcart_item_product_asv);
            viewHolder.soldOut = (TextView) convertView.findViewById(R.id.tv_toast_sold_out);
            viewHolder.favoriteBtn = (Button) convertView.findViewById(R.id.shoppingcart_item_product_favorite);
            viewHolder.listPrice = (TextView) convertView.findViewById(R.id.shoppingcart_item_product_listprice);
            viewHolder.listPriceContain = (RelativeLayout) convertView.findViewById(R.id.shoppingcart_item_product_listprice_contain);
            viewHolder.freeMark = (ImageView) convertView.findViewById(R.id.shoppingcart_item_product_freemark);
            viewHolder.giftQty = (TextView) convertView.findViewById(R.id.shoppingcart_item_product_giftqty);

            viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.cb_shoppingcart_item);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
//        viewHolder.addSubtracterView.setCanShowDialog(isShoppingCart);
        viewHolder.addSubtracterView.setCanShowDialog(false);
        if (!isShoppingCart) {
            viewHolder.productFree.setVisibility(View.INVISIBLE);
        } else {
            viewHolder.productFree.setVisibility(View.VISIBLE);
        }
        String filePath = getImageUrl(densityDpi, productModel, 186, 240);
        if (URLUtil.isHttpUrl(filePath) || URLUtil.isHttpsUrl(filePath)) {
            viewHolder.productThmb.setTag(filePath);
            ImageLoader.getInstance().displayImage(filePath, viewHolder.productThmb, options);

        } else {
            viewHolder.productThmb.setImageBitmap(ActivityUtil.getDefault488(mContext));
        }

        viewHolder.addSubtracterView.setOnNumChangeListener(this);
        viewHolder.addSubtracterView.setTag(position);

        viewHolder.productName.setText(productModel.getShortHeadLine1());
        viewHolder.productPrice.setText((TextUtils.isEmpty(currencyCodeStr) ? "" : currencyCodeStr) + StringUtil.getPrice(productModel.getPrice()));
        viewHolder.productFree.setText(R.string.product_freeship_);
//        if(productModel.getPrice()>=15f){
//        	viewHolder.productFree.setVisibility(View.VISIBLE);
//        }else {
//        	viewHolder.productFree.setVisibility(View.GONE);
//        }

        if (productModel.getlistprice() > productModel.getPrice()) {//如果销售价格小于原价，则显示原价并置灰划掉
            viewHolder.listPriceContain.setVisibility(View.VISIBLE);
            viewHolder.listPrice.setText((TextUtils.isEmpty(currencyCodeStr) ? "" : currencyCodeStr) + StringUtil.getPrice(productModel.getlistprice()));
        } else {
            viewHolder.listPriceContain.setVisibility(View.INVISIBLE);
        }
        //设置库存上限为最大值
        SalesLimit salesLimit = productModel.getSalesLimit();
        viewHolder.soldOut.setVisibility(View.INVISIBLE);
        if (salesLimit == null || salesLimit.getDistributionPolicy() == 2) {
            viewHolder.soldOut.setVisibility(View.INVISIBLE);
            //不限量
            viewHolder.addSubtracterView.setNum(productModel.getQuantity());
            viewHolder.addSubtracterView.setMaxNumber(9999999);
            viewHolder.addSubtracterView.setLimitNum(9999999);
        } else {
            viewHolder.addSubtracterView.setLimitNum(salesLimit.getSalesLimitQty());
            if (salesLimit.getDistributionPolicy() == 1) {
                //限量
                viewHolder.addSubtracterView.setMaxNumber(salesLimit.getSalesLimitQty());
                int salesLimitNum = salesLimit.getSalesLimitQty();
//        		 if (salesLimitNum >= productModel.getQuantity()||salesLimitNum==0)
                if (productModel.getOrderedQty() == productModel.getRequestQty()) {
                    viewHolder.addSubtracterView.setNum(productModel.getQuantity());
                } else {
                    //超过库存修改订购数量为库存最大值
                    viewHolder.addSubtracterView.setNum(salesLimitNum);
                    onNumChange(viewHolder.addSubtracterView, salesLimitNum, false, true);
                    viewHolder.soldOut.setVisibility(View.VISIBLE);
                    String tips = mContext.getString(R.string.product_inventory_limit, salesLimit.getSalesLimitQty());
                    viewHolder.soldOut.setText(tips);
                }
            }
            if (salesLimit.getDistributionPolicy() == 0) {
                //无货
                viewHolder.addSubtracterView.setNum(productModel.getQuantity());
                viewHolder.soldOut.setVisibility(View.VISIBLE);
                viewHolder.soldOut.setText(R.string.sold_out);
            }
        }
        String isFavorite = productModel.getIsFavorite();
        if (null != isFavorite && "true".equals(isFavorite)) {
            viewHolder.favoriteBtn.setBackgroundResource(R.drawable.shoppingcart_item_heart_on);
        } else {
            viewHolder.favoriteBtn.setBackgroundResource(R.drawable.shoppingcart_item_heart_off);
        }

        viewHolder.favoriteBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (null != btnListenner) {
                    btnListenner.favoriteBtnOnclick(productModel.getSku(), position);
                }
            }
        });
        //如果是赠送的SKU，做相应的UI与事件处理
        if (productModel.isGift()) {
            //显示左上角标记图标
            viewHolder.freeMark.setVisibility(View.VISIBLE);
            //隐藏加减按钮，只显示数量
            viewHolder.addSubtracterView.setVisibility(View.INVISIBLE);
            viewHolder.giftQty.setVisibility(View.VISIBLE);
            viewHolder.giftQty.setText("x" + productModel.getQuantity());
            //设置数量为服务端获取的数量
            viewHolder.addSubtracterView.setNum(productModel.getQuantity());
            //将价格置为0，原价置灰划线显示
            viewHolder.productPrice.setText((TextUtils.isEmpty(currencyCodeStr) ? currencyCode : currencyCodeStr) + StringUtil.getPrice(0));
            viewHolder.listPriceContain.setVisibility(View.VISIBLE);
            viewHolder.listPrice.setText((TextUtils.isEmpty(currencyCodeStr) ? currencyCode : currencyCodeStr) + StringUtil.getPrice(productModel.getPrice()));
        } else {
            viewHolder.freeMark.setVisibility(View.GONE);
            viewHolder.addSubtracterView.setVisibility(View.VISIBLE);
            viewHolder.giftQty.setVisibility(View.INVISIBLE);
        }

        viewHolder.checkBox.setEnabled(isShoppingCart);
        viewHolder.checkBox.setVisibility(isShoppingCart ? View.VISIBLE : View.GONE);

        viewHolder.checkBox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isChecked = ((CheckBox) v).isChecked();
                cbSelectes.put(productModels.get(position).getSku(), isChecked);
                onSelectChange(position);
                synchronizeCheck();
            }
        });
        Boolean checked = cbSelectes.get(productModels.get(position).getSku());
        if (checked == null) {
            checked = true;
        }
        viewHolder.checkBox.setChecked(checked);

        return convertView;
    }

    public boolean isCheckOne(){
        boolean inOne = false;
        for (int i = 0; i < productModels.size(); i++) {
            int sku = productModels.get(i).getSku();
            if (cbSelectes.get(sku) != null
                    && cbSelectes.get(sku)) {
                inOne = true;
                break;
            }
        }
        return inOne;
    }
    private void synchronizeCheck() {
        boolean isAll = true;
        for (int i = 0; i < productModels.size(); i++) {
            int sku = productModels.get(i).getSku();
            if (cbSelectes.get(sku) == null
                    || !cbSelectes.get(sku)) {
                isAll = false;
                break;
            }
        }

        if (null != changeListenner && changeListenner instanceof ShoppingCartFragment) {
            ((ShoppingCartFragment) changeListenner).synchronizeCheck(isAll);
        }

    }

    public void update() {
        for (int i = 0; i < productModels.size(); i++) {
            int sku = productModels.get(i).getSku();
            if (cbSelectes.get(sku) == null) {
                cbSelectes.put(sku, true);
            }
        }
        notifyDataSetChanged();
        synchronizeCheck();
    }

    public String getNotSelectedSkuStr() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < productModels.size(); i++) {
            if (!cbSelectes.get(productModels.get(i).getSku())) {
                sb.append(productModels.get(i).getSku());
                sb.append(",");
            }
        }
        if (sb.toString().endsWith(",")) {
            return sb.toString().substring(0, sb.length() - 1);
        }
        return sb.toString();
    }

    public List<Integer> getNotSelectedSkus() {
        List<Integer> noSkus = new ArrayList<Integer>();
        for (int i = 0; i < productModels.size(); i++) {
            if (!cbSelectes.get(productModels.get(i).getSku())) {
                noSkus.add(productModels.get(i).getSku());
            }
        }
        return noSkus;
    }

    public boolean getCheck(int sku) {
        return cbSelectes.get(sku);
    }

    public void check(boolean isChecked) {
        for (int i = 0; i < getCount(); i++) {
            cbSelectes.put(getItem(i).getSku(), isChecked);
        }
        notifyDataSetChanged();
    }

    class ViewHolder {
        ImageView productThmb;

        TextView productName;

        TextView productPrice;

        TextView productFree;

        TextView soldOut;

        AddSubtracterView addSubtracterView;

        Button favoriteBtn;

        TextView listPrice;

        RelativeLayout listPriceContain;

        ImageView freeMark;

        TextView giftQty;

        CheckBox checkBox;
    }

    private void onSelectChange(int position) {
        OrderProductModel productModel = productModels.get(position);
        if (null != changeListenner && changeListenner instanceof ShoppingCartFragment) {
            ((ShoppingCartFragment) changeListenner).updateSelected(productModel);
        }
    }

    @Override
    public void onNumChange(View view, int num, boolean isAdd, boolean isLimitChange) {
        // 数量变动更新本地数据库和总价
        int position = (Integer) view.getTag();
        OrderProductModel productModel = productModels.get(position);
        productModel.setQuantity(num);
        Logger.i("TAG---", num + " onNumChange ");
        if (null != changeListenner) {
            changeListenner.changeProductNum(productModel, isAdd, isLimitChange);
        }
    }

    public interface FavoriteBtnListenner {
        void favoriteBtnOnclick(int sku, int position);
    }

    public void setFavoriteListenner(FavoriteBtnListenner listenner) {
        this.btnListenner = listenner;
    }

    @Override
    public void toDeleteItem(View view) {
        int position = (Integer) view.getTag();
        if (null == productModels || position >= productModels.size()) {
            return;
        }
        OrderProductModel productModel = productModels.get(position);
        if (null != changeListenner) {
            changeListenner.deleteProductItem(productModel);
        }
        //fragment.showDeleteDialog(productModel);
    }


    public interface OnProductChangeListenner {
        void deleteProductItem(OrderProductModel productModel);

        void changeProductNum(OrderProductModel productModel, boolean isAdd, boolean isLimitChange);
    }

    /**
     * 设置币种简写与符号
     *
     * @param currencyCode
     * @param currencyCodeStr
     */
    public void setCurrencyCode(String currencyCode, String currencyCodeStr) {
        this.currencyCode = currencyCode;
        this.currencyCodeStr = currencyCodeStr;
    }
}
